<template>
  <div class="product-list-view">
    <el-container>
      <product-category-filter
        :fold="categoryFilterShow"
        :cid.sync="cid"
        :cname.sync="cname"
      />
      <div style="flex: 1">
        <el-collapse>
          <el-collapse-item>
            <template #title>
              <div
                style="
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                  width: 50%;
                "
              >
                <el-button-group>
                  <el-button
                    size="mini"
                    plain
                    icon="el-icon-collection"
                    @click.stop="categoryFilterShow = !categoryFilterShow"
                  ></el-button>
                  <el-button
                    size="mini"
                    plain
                    icon="el-icon-search"
                  ></el-button>
                  <el-button
                    size="mini"
                    plain
                    icon="el-icon-refresh-right"
                    @click.stop="fresh"
                  ></el-button>
                </el-button-group>
                <tag-group :tag-list.sync="tagList" />
              </div>
            </template>
            <product-list-filter :filter.sync="filter" />
          </el-collapse-item>
        </el-collapse>

        <el-table :data="productList" border highlight-current-row stripe>
          <el-table-column
            prop="id"
            label="编号"
            width="80px"
          ></el-table-column>
          <el-table-column prop="name" label="商品名称"></el-table-column>
          <el-table-column prop="short_desc" label="商品简述"></el-table-column>
          <el-table-column label="商品展示图片" width="250px">
            <template v-slot="{ row }">
              <el-image
                :src="row && row.display_image"
                style="width: 50px; height: 50px"
                fit="scale-down"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column label="商品图片" width="250px">
            <template v-slot="{ row }">
              <div v-if="row && row.images.length > 0">
                <el-image
                  :src="row.images[0].image"
                  style="width: 50px; height: 50px"
                  fit="scale-down"
                ></el-image>
                <span>共{{ row.images.length }}张</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="price"
            label="商品原价"
            width="80px"
          ></el-table-column>
          <el-table-column
            prop="sale_price"
            label="商品售价"
            width="80px"
          ></el-table-column>
          <el-table-column
            prop="stock"
            label="商品库存"
            width="80px"
          ></el-table-column>
          <el-table-column label="所属类别">
            <template v-slot="{ row }">
              {{
                row &&
                row.category_name_path &&
                row.category_name_path.join(" / ")
              }}
            </template>
          </el-table-column>
          <el-table-column label="是否上架">
            <template v-slot="{ row }">
              <el-switch
                active-color="#13ce66"
                inactive-color="red"
                :value="row && row.is_published"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="created" label="创建时间">
            <template v-slot="{ row }">
              {{ $dayjs(row && row.created).format("YYYY-MM-DD HH:mm:ss") }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-link
                icon="el-icon-edit"
                type="primary"
                :underline="false"
                @click="onEdit(row)"
              >
                编辑
              </el-link>
              <el-link
                icon="el-icon-delete"
                type="danger"
                :underline="false"
                @click="onDelete(row)"
                v-permission="
                  $route.meta.permission && $route.meta.permission.delete
                "
              >
                删除
              </el-link>
              <el-link icon="el-icon-view" type="warning" :underline="false">
                详情预览
              </el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-container>
    <!--编辑页面对话框-->
    <el-dialog :visible="isEdit" :before-close="closeDialog">
      <product-edit-view :product="editProductObj" @update="onUpdate" />
    </el-dialog>
    <div
      style="
        display: flex;
        align-items: center;
        justify-content: center;
        height: 60px;
      "
    >
      <el-pagination
        :current-page.sync="pagination.page"
        :page-size.sync="pagination.size"
        :page-sizes="[20, 40, 60, 80]"
        layout="sizes,total, prev, pager, next"
        :total="count"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import * as types from "@/store/types";
import { mapActions, mapGetters, mapMutations } from "vuex";
import { clearSelectedProduct } from "../../../store/utils";
import ProductCategoryFilter from "./ProductCategoryFilter";
import ProductListFilter from "./ProductListFilter";
import TagGroup from "../../../components/TagGroup";
import { treeFind } from "../../../utils/tree";
import ProductEditView from "../edit/ProductEditView";
import { deleteApiCache } from "../../../utils/cache";

export default {
  name: "ProductListView",
  components: {
    ProductEditView,
    TagGroup,
    ProductListFilter,
    ProductCategoryFilter,
  },
  data() {
    return {
      editProductObj: {},
      isEdit: false,
      categoryFilterShow: false,
      results: [],
      pagination: {
        size: 20,
        page: 1,
      },
      count: 0,
      cid: -1,
      cname: "",
      filter: {
        key: "",
        maxPrice: "",
        minPrice: "",
        beginTime: "",
        endTime: "",
      },
    };
  },
  computed: {
    ...mapGetters(["getProductList", "treeCategory"]),
    productList() {
      return this.getProductList(this.results);
    },
    // 生成各种查询参数 page/size/cid/key/maxPrice/minPrice
    query() {
      const query = {};
      if (this.cid !== -1) {
        query.cid = this.cid;
      }
      const pagination = { ...this.pagination };
      if (pagination.size == 20) {
        delete pagination.size;
      }
      if (pagination.page == 1) {
        delete pagination.page;
      }

      Object.assign(query, pagination); //合并两个对象

      const filter = { ...this.filter };
      for (let key in filter) {
        if (!filter[key]) {
          delete filter[key];
        }
      }
      Object.assign(query, filter);

      return query;
    },
    tagList: {
      //  getter
      get() {
        const tagList = [];
        for (let key in this.query) {
          switch (key) {
            case "cid":
              tagList.push({ label: "商品类别", key, value: this.cname });
              break;
            case "key": {
              tagList.push({ label: "关键字", key, value: this.query[key] });
              break;
            }
            case "maxPrice": {
              tagList.push({ label: "最高价", key, value: this.query[key] });
              break;
            }
            case "minPrice": {
              tagList.push({ label: "最低价", key, value: this.query[key] });
              break;
            }
            case "beginTime": {
              tagList.push({ label: "开始时间", key, value: this.query[key] });
              break;
            }
            case "endTime": {
              tagList.push({ label: "结束时间", key, value: this.query[key] });
              break;
            }
            default:
              break;
          }
        }
        return tagList;
      },
      //  setter
      set(data) {
        const { key } = data;
        if (key === "cid") {
          this.cid = -1;
        } else {
          this.filter[key] = "";
        }
      },
    },
  },
  methods: {
    ...mapMutations([types.EDIT_PRODUCT, types.DELETE_PRODUCT]),
    ...mapActions([types.SET_PRODUCT]),
    //更新vuex中的商品数据
    onUpdate(data) {
      this[types.EDIT_PRODUCT](data);
    },
    fresh() {
      clearSelectedProduct(this.results);
      this.getProduct();
    },
    async getProduct() {
      // 先获取要显示的商品的ID
      const { page, count, results } = await this.$api.getProductIds(
        // this.pagination
        this.query
      );
      this.pagination.page = page;
      this.count = count;

      //记录下当前要显示的商品的id的数组
      this.results = results;

      // 调用vuex中设置商品缓存的方法
      await this[types.SET_PRODUCT](results);
    },
    //编辑商品
    onEdit(data) {
      // console.log("editData", data);
      this.isEdit = true;
      this.editProductObj = { ...data };
    },
    //删除商品
    async onDelete(data) {
      // // console.log(data.id)
      // // const { id } = data;
      // const result = await deleteProduct(data);
      // console.log("result", result);
      // await this.getProduct();
      await this.$api.deleteProduct(data);
      // 从vuex删除
      this[types.DELETE_PRODUCT](data);
      // 删除api的缓存
      deleteApiCache("/product/id/" + JSON.stringify(this.query));

      //  重新请求数据
      this.getProduct();
    },
    //  关闭对话框
    closeDialog() {
      this.isEdit = false;
    },
  },
  async created() {
    // console.log(this.$route.query)
    const query = this.$route.query;
    for (let [key, value] of Object.entries(query)) {
      if (key === "cid") {
        this.cid = Number(value);
        const node = treeFind(
          this.treeCategory,
          (node) => node.id === this.cid
        );
        this.cname = node.name;
      } else if (key === "page") {
        this.pagination.page = Number(value);
      } else if (key === "size") {
        this.pagination.size = Number(value);
      } else {
        this.filter[key] = value;
      }
    }
    await this.getProduct();
  },
  watch: {
    query: {
      deep: true,
      handler() {
        this.getProduct();
        // this.$router 路由器
        this.$router
          .push({ path: this.$route.path, query: this.query })
          .catch((err) => {
            return Promise.reject(err);
          });
      },
    },
    ["getProduct.length"](val) {
      if (val < this.pagination.size) {
        console.log("watch");
        this.getProduct();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.el-collapse {
  /*background-color: red;*/
  /*border: none;*/

  ::v-deep.el-collapse-item__content {
    padding-bottom: 0;
  }
}
.el-table {
  width: 90%;
  height: 500px;
  overflow: auto;
  /*background-color: red;*/
}
</style>
